package models
{
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.MouseEvent;
	import flash.media.Microphone;
	import flash.utils.ByteArray;

	import org.as3wavsound.WavSound;
	import org.as3wavsound.WavSoundChannel;
	import org.bytearray.micrecorder.MicRecorder;
	import org.bytearray.micrecorder.encoder.WaveEncoder;
	import org.bytearray.micrecorder.events.RecordingEvent;

	public class RecordAudio extends EventDispatcher
	{
		public function RecordAudio()
		{
		}

		private static var _instance:RecordAudio;

		public static function get instance():RecordAudio
		{
			if(!_instance)
				_instance=new RecordAudio();
			return _instance;
		}

		public function init():void
		{
			dispose();

			recording=false;

			recorder=new MicRecorder( new WaveEncoder(),Microphone.getMicrophone(),60,44,0,1000)
			recorder.addEventListener(RecordingEvent.RECORDING, onRecording);
			recorder.addEventListener(Event.COMPLETE, onRecordComplete);
		}

		public function clearRecord():void
		{
			if(wavData)
				wavData.clear();
			wavData=null;
			recorded=false;

			if(sc)
			{
				sc.stop();
				sc=null;
			}
			snd=null;
		}

		public function stopRecord():void
		{
			recorder.stop();
		}

		public function stopReplay():void
		{
			playing=false;	
			if(sc)
				sc.stop();
		}

		public function playRecord(wav:ByteArray):void
		{
			if(!snd)
			{
				if(wav)
					snd=new WavSound(wav);
			}
			if(snd)
			{
				sc=snd.play(0);
				sc.addEventListener(Event.SOUND_COMPLETE,onReplayComplete);
				playing=true;
			}
		}

		protected function onReplayComplete(event:Event):void
		{
			dispatchEvent(new Event('playComplete'));
			if(sc)
			{
				sc.stop();
			}
			playing=false;
		}

		protected function onRecording(event:RecordingEvent):void
		{
		}

		protected function onRecordComplete(event:Event):void
		{
			recording=false;
			initData(recorder.output);
		}

		public function startRecord():void
		{
			recording=true;
			recorder.record();
		}

		public function initData(data:ByteArray):void
		{
			wavData=data;
			if(wavData)
				recorded=true;

			snd=null;
		}

		public function getBA():ByteArray
		{
			return wavData;
		}

		public function dispose():void
		{
			if(recorder&&recorder.output)
				recorder.output.clear();
			recorder=null;
			snd=null;
			sc=null;
		}

		private var recorder:MicRecorder;

		private var snd:WavSound;

		private var sc:WavSoundChannel;
		private var wavData:ByteArray;
		private var playing:Boolean;
		private var recording:Boolean;
		private var recorded:Boolean;
	}
}

